class Sidebar {
  constructor(options = {}) {
    this.options = {
      sidebarId: "mySidebar",
      baseWidth: 800, // 基准宽度
      baseHeight: 600, // 基准高度
      ...options,
    };

    this.isVisible = true;
    this.hideButton = null;

    // 添加自定义事件
    this.events = {};

    // 计算并设置缩放比例
    this.updateScale();

    // 监听窗口大小变化
    window.addEventListener("resize", () => this.updateScale());

    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", () => this.init());
    } else {
      this.init();
    }
  }

  updateScale() {
    const scaleX = window.innerWidth / this.options.baseWidth;
    const scaleY = window.innerHeight / this.options.baseHeight;
    const scale = Math.min(scaleX, scaleY);

    // 设置CSS变量
    document.documentElement.style.setProperty("--scale-ratio", scale);
  }

  init() {
    this.sidebar = document.getElementById(this.options.sidebarId);

    if (!this.sidebar) {
      console.error("Sidebar: 无法找到必要的DOM元素");
      return;
    }

    // 修改隐藏按钮的创建和定位
    this.hideButton = document.createElement("button");
    this.hideButton.className = "hide-sidebar-btn";
    this.hideButton.innerHTML = "◀";
    this.sidebar.appendChild(this.hideButton);

    this.hideButton.addEventListener("click", () => this.toggleVisibility());

    // 初始化完成后更新一次缩放
    this.updateScale();

    console.log("初始化完毕");
    this.toggleVisibility();
  }

  toggleSidebar() {
    this.sidebar.classList.toggle("active");
  }

  openSidebar() {
    this.sidebar.classList.add("active");
  }

  closeSidebar() {
    this.sidebar.classList.remove("active");
  }

  toggleVisibility() {
    this.isVisible = !this.isVisible;

    if (this.isVisible) {
      // 显示状态
      this.sidebar.classList.remove("hidden");
      this.hideButton.innerHTML = "◀";
    } else {
      // 隐藏状态
      this.sidebar.classList.add("hidden");
      this.hideButton.innerHTML = "▶";
    }
  }

  // 添加事件监听方法
  on(eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(callback);
  }

  // 触发事件的方法
  emit(eventName, data) {
    if (this.events[eventName]) {
      this.events[eventName].forEach((callback) => callback(data));
    }
  }
}
